package com.wqh.ice_storm;

import com.wqh.ice_storm.Service.ReportServiceImpl;
import com.zeroc.Ice.Communicator;
import com.zeroc.Ice.Object;
import com.zeroc.Ice.ObjectAdapter;
import com.zeroc.Ice.ObjectPrx;
import com.zeroc.Ice.Util;
import com.zeroc.IceStorm.*;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Logger;

public class Subscriber {
    private static Logger logger = Logger.getLogger(Subscriber.class.getSimpleName());

    public static void main(String[] args) {
        getMessage(args);
    }

    public static void getMessage(String[] args) {

        String topicName = "weather";
        //初始化通信器
        java.util.List<String> extraArgs = new java.util.ArrayList<>();
        try(Communicator com  = Util.initialize(args,"config.sub",extraArgs)) {
            //销毁通信器
            Runtime.getRuntime().addShutdownHook(new Thread(() -> com.destroy()));

            com.getProperties().setProperty("Ice.Default.Package", "com.zeroc.demos.IceStorm.weather");



            //"IceStorm/TopicManager"发布端通信定义的名称
            //ObjectPrx obj = com.stringToProxy("WeatherService/TopicManager:tcp -p 10000");
            ObjectPrx obj = com.propertyToProxy("TopicManager.Proxy");

            TopicManagerPrx topicManagerPrx = TopicManagerPrx.checkedCast(obj);
            //客户端创建适配器
            ObjectAdapter adapter = com.createObjectAdapter("Weather.Subscriber");

            Object reportService = new ReportServiceImpl();
            //将服务的具体实现类servant提交给适配器
            ObjectPrx proxy = adapter.addWithUUID(reportService).ice_oneway();

            TopicPrx topic = null;
            //搜索指定主题
            try {
                topic = topicManagerPrx.retrieve(topicName);
                //？？？？
                Map qos = new HashMap();
                topic.subscribeAndGetPublisher(qos,proxy);
            } catch (NoSuchTopic noSuchTopic) {
                logger.info("未找到指定主题");
                noSuchTopic.printStackTrace();
            } catch (AlreadySubscribed alreadySubscribed) {
                alreadySubscribed.printStackTrace();
            } catch (InvalidSubscriber invalidSubscriber) {
                invalidSubscriber.printStackTrace();
            } catch (BadQoS badQoS) {
                badQoS.printStackTrace();
            }
            //激活适配器
            adapter.activate();
            logger.info("客户端已经启动");

            com.waitForShutdown();
        }
    }
}
